<?php
namespace control;

/*
*其他收支明细表类
*/

class otherDetailsClass extends adIndexClass
{
    private const page = 'otherDetails';
    private const table='other_receipt';
    private const tableMx='other_receipt_detail';
    private const title = '其他收支明细表';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => L('finance.table.ri_qi'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'orderNo'  => [
                        'name'  => L('finance.table.dan_ju_bian_hao'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'classify'         => [
                        'name'  => L('finance.table.ye_wu_lei_xing'),
                        'width' => 200,
                    ],
                    'project'          => [
                        'name'  => L('finance.table.szxm'),
                        'width' => 200,
                    ],
                    'in'          => [
                        'name'  => L('finance.table.income').'(' . static::$unit . ')',
                        'width' => 200,
                    ],
                    'out'          => [
                        'name'  => L('finance.table.expenditure').'(' . static::$unit . ')',
                        'width' => 200,
                    ],
                    'targetName'          => [
                        'name'  => L('finance.table.wldw'),
                        'width' => 200,
                    ],
                    'text'          => [
                        'name'  => L('finance.table.bei_zhu'),
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('finance.table.ri_qi') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    L('finance.table.ye_wu_lei_xing')   => select(["name" => "type", 'option' => ['2'=>L('finance.table.qi_ta_shou_ru'), '1'=>L('finance.table.qi_ta_zhi_chu')]]),
                    L('finance.table.szxm') => select(["name" => "project", 'option' => para('cashClassify','，')]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array();
        //全等查询数组
        $equal = array(
            'a.coid' => self::$coid,
            'a.state'=>'已确认',
            'a.classify' => $this->post('type'),
            'b.project' => $this->post('project'),
        );
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table." as a join ".self::tableMx." as b on a.id = b.orderId",
            'field'=>"a.recordDate,a.orderNo,a.classify,b.*,a.targetName",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            if ($array['classify']==2) {
                //支出
                $out = $array['money'];
                $in = 0;
            } else {
                $out = 0;
                $in =$array['money'];
            }
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'classify':
                        $row[] = $array['classify']==2?L('finance.table.qi_ta_zhi_chu'):L('finance.table.qi_ta_shou_ru');
                        break;
                    case 'in':
                        $row[] = $in;
                        break;
                    case 'out':
                        $row[] = $out;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $total = find([
            'table'  => self::table." as a join ".self::tableMx." as b on a.id = b.orderId",
            'single' => $where,
            'field'  => "sum(if(a.classify=2,b.money,0))outMoney,sum(if(a.classify=2,0,b.money))inMoney ",
        ]);
        $total    = [
            'in'        => self::lostZero($total['inMoney']),
            'out'   => self::lostZero($total['outMoney']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = "您还没有导出的权限";
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by list asc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                if ($array['classify']==2) {
                    //支出
                    $out = $array['money'];
                    $in = 0;
                } else {
                    $out = 0;
                    $in =$array['money'];
                }
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '日期'=>$array['recordDate'],
                            '单据编号'=>$array['orderNo'],
                            '业务类型'=>$array['classify']==2?L('finance.table.qi_ta_zhi_chu'):L('finance.table.qi_ta_shou_ru'),
                            '收支项目'=>$array['project'],
                            '收入'=>$in,
                            '支出'=>$out,
                            '往来单位'=>$array['targetName'],
                            '备注'=>$array['text'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = str_replace(['{{staffName}}'],[$this->control['name']],L('finance.table.other_export_text'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('finance.table.otherDetail').".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',
                ],
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'业务类型',
                    'aliasName'=>'业务类型',
                ],
                [
                    'columnName'=>'收支项目',
                    'aliasName'=>'收支项目',
                ],
                [
                    'columnName'=>'收入',
                    'aliasName'=>'收入(元)',
                ],
                [
                    'columnName'=>'支出',
                    'aliasName'=>'支出(元)',
                ],
                [
                    'columnName'=>'往来单位',
                    'aliasName'=>'往来单位',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
            ]
        };
    }
}

